package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * Selector Demo
 */
public class NioDemo4 {

    public static void main(String[] args) throws IOException {

        int[] ports = {5000,5001,5002,5003,5004};

        Selector selector = Selector.open();

        for (int port : ports) {
            ServerSocketChannel socketChannel = ServerSocketChannel.open();
            socketChannel.configureBlocking(false);
            ServerSocket socket = socketChannel.socket();
            InetSocketAddress address = new InetSocketAddress(port);
            socket.bind(address);

            socketChannel.register(selector, SelectionKey.OP_ACCEPT);

            System.out.println("监听端口：" + port);
        }

        while (true){
            int num = selector.select();
            System.out.println(num);

            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            System.out.println("selectionKeys"+selectionKeys);

            Iterator<SelectionKey> iterator = selectionKeys.iterator();

            while (iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();

                if (selectionKey.isAcceptable()){
                    ServerSocketChannel channel = (ServerSocketChannel)selectionKey.channel();

                    SocketChannel socketChannel = channel.accept();
                    socketChannel.configureBlocking(false);

                    socketChannel.register(selector,SelectionKey.OP_READ);

                    iterator.remove();

                    System.out.println("获取客户端连接:"+socketChannel);
                }else if (selectionKey.isReadable()){
                    SocketChannel channel = (SocketChannel) selectionKey.channel();

                    int byteRead = 0;

                    while (true){
                        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

                        byteBuffer.clear();

                        int read = channel.read(byteBuffer);

                        if (read<=0){
                            break;
                        }

                        byteBuffer.flip();

                        channel.write(byteBuffer);

                        byteRead+=read;
                    }
                    System.out.println("读取："+byteRead+"，来自于："+channel);
                    iterator.remove();
                }

            }
        }

    }
}
